package com.txr.news.controller;

import com.txr.news.customexception.SystemException;
import com.txr.news.pojo.ExType;
import com.txr.news.pojo.Result;
import com.txr.news.pojo.ResultArticle;
import com.txr.news.pojo.entity.Article;
import com.txr.news.service.ArticleService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@CrossOrigin
@RequestMapping("/my/article")
@AllArgsConstructor
public class ArticleController {
    ArticleService articleService;

    @PostMapping("/add")
    public Result addArticle(HttpServletRequest request, String title, Integer cate_id,
                             String content, MultipartFile cover_img, String state){
        Result result = new Result(0,"发布文章成功！");
        try {
            Integer authorId = (Integer) request.getAttribute("userId");
            String realPath = request.getSession().getServletContext().getRealPath("/"); //得到文件的真实路径
            System.out.println(realPath);
            if (cover_img != null){
                String randomUUID = UUID.randomUUID().toString();
                String filename = "uploads/" + randomUUID;
                File newFile = new File(realPath + "uploads/" + randomUUID); //创建文件
                cover_img.transferTo(newFile); //把cover_img写入到文件里

                //获取当前系统时间
                Date day = new Date();
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String pubDate = df.format(day);

                Article article = new Article(null,title,filename,pubDate,state,null,cate_id,authorId,content);
                Boolean flag = articleService.addArticle(article);
                if (!flag){
                    result.setStatus(1);
                    result.setMsg("发布文章失败！");
                    return result;
                }
            }
            return result;
        } catch (IOException e) {
            throw new SystemException("io Exception", ExType.SystemIOFail, e);
        }
    }

    @GetMapping("/list")
    public ResultArticle getArticleList(int pagenum, int pagesize, String cate_id, String state){
        System.out.println("pagenum="+pagenum);
        System.out.println("pagesize="+pagesize);
        System.out.println("cate_id="+cate_id);
        try {
            byte[] bytes = state.getBytes("ISO-8859-1");
            state = new String(bytes,"UTF-8");
            System.out.println("state="+state);
            ResultArticle ret = articleService.getArticleList(pagenum, pagesize, cate_id, state);
            return ret;
        } catch (UnsupportedEncodingException e) {
            throw new SystemException("Unsupported Encoding Exception", ExType.SystemEncodingFail,e);
        }
    }

    @GetMapping("/delete/{id}")
    public Result deleteArticle(@PathVariable String id){
        Result result = new Result(0,"删除文章成功！");
        Boolean flag = articleService.deleteArticle(id);
        if (!flag){
            result.setStatus(1);
            result.setMsg("删除文章失败！");
        }
        return result;
    }

    @GetMapping("/{id}")
    public Result getArticleById(@PathVariable String id){
        Result result = new Result(0,"获取文章成功！");
        if (id == null || id.equals("")){
            throw new SystemException("id is null",ExType.SystemFail);
        }
        Integer article_id = Integer.parseInt(id);
        Article article = articleService.getArticleById(article_id);
        if (article == null){
            result.setStatus(1);
            result.setMsg("获取文章失败！");
        }
        System.out.println("这是图片："+article.getCoverImg());
        result.setData(article);
        return result;
    }
}
